import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { ModelServiceProxy, ModelEditDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';

import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditModelModal',
    templateUrl: './create-or-edit-model.modal.component.html'
})
export class CreateOrEditModelModalComponent extends AppComponentBase {
    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    model: ModelEditDto = new ModelEditDto();

    constructor(injector: Injector, private _modelService: ModelServiceProxy) {
        super(injector);
    }

    show(modelId?: number): void {
        this.active = true;

        this._modelService.getModelForEdit(modelId).subscribe(result => {
            this.model = result.model;

            this.modal.show();
        });
    }

    save(): void {
        this.saving = true;

        this._modelService
            .createOrUpdateModel(this.model)
            .pipe(finalize(() => (this.saving = false)))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
